package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author Mr.Wen
 * @Version 1.0
 * 定义Redis全局唯一Id
 */
@Component
public class RedisIDWorker {
    /**
     * 自增长ID
     */
    private static final Long BEGIN_TIMESTAMP = 1704067200L;
    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 生成时间戳
        long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMP;
        // 生成序列号
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 获取当前日期的自增id，精确到天
        Long incrCount = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);

        // 拼接并返回
        /*时间戳逻辑左移32位*/
        return timestamp << COUNT_BITS | incrCount;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second = " + second);
    }
}
